package com.aj.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aj.activity.adapter.FamilyPhotoGridAdapter;
import com.aj.activity.adapter.FamilyUserAdapter;
import com.aj.activity.view.SpecialHorizontalScrollView;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.HomeDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Family;
import com.aj.databases.entry.FamilySpace;
import com.aj.databases.entry.FamilyZoneInfo;
import com.aj.databases.entry.Home;
import com.aj.databases.entry.User;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.AlbumManagerRequest;
import com.aj.http.request.FamilyZoneRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.Common;
import com.aj.http.response.FamilyZoneResponse;
import com.aj.utils.Contants;
import com.aj.utils.UIUtil;
import com.easemob.chatuidemo.activity.ChatActivity;

public class FamilySpaceActivity extends BaseActivity {
	private final static String TAG = FamilySpaceActivity.class.getName();
	private GridView head_grid;
	private GridView photo_body;
	private Button sure_or_cannelbutton;
	private SpecialHorizontalScrollView head_tools_linearlayout;
	private LinearLayout date_grid_layout;
	private TextView update_name_text;
	private TextView delete_text;
	private TextView delete_all_text;
	private Family family;
	private Home home;
	private HomeDao homeDao;
	private String selfPageFlag = "";
	private FamilyPhotoGridAdapter familyPhotoGridAdapter;
	private FamilyUserAdapter familyUserAdapter;
	private List<FamilySpace> familySpaceList;
	private List<FamilyZoneInfo> familyZoneInfoList;
	private boolean isManageFlag = false;

	@Override
	protected void onResume() {
		super.onResume();
		// new AddFamilyRequest().excute(FamilySpaceActivity.this,
		// family.getUserid(), "1", "老汉", "AJN00034", "1", "18723405559",
		// new IHttpCallBack() {
		// @Override
		// public void success(String result) {
		// try {
		// Common common = new Common(new JSONObject(result));
		// if (common != null
		// && common
		// .getReturnCode()
		// .equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
		// new SureFamilyRequest().excute(
		// FamilySpaceActivity.this, "37", "32",
		// "0", new IHttpCallBack() {
		// @Override
		// public void success(String result) {
		//
		// }
		//
		// @Override
		// public void fail(String result) {
		//
		// }
		// });
		// }
		//
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
		// }
		//
		// @Override
		// public void fail(String result) {
		//
		// }
		// });
		home = homeDao.getHome(family.getHome().getId());
		if (home == null) {
			Toast.makeText(this, getString(R.string.familyspace_nofamily_text),
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		resume();
	}

	private void resume() {
		showProgressDialog();
		// new ManagerChildRequest().excute(this, family.getUserid(), "1", null,
		// "0", null, "幺儿", "贵贵", "0", "2015-04-19", null, "1", null, "7",
		// "描述", new IHttpCallBack() {
		// @Override
		// public void success(String result) {
		//
		// }
		//
		// @Override
		// public void fail(String result) {
		//
		// }
		// });

		new FamilyZoneRequest().excute(this, family.getUserid(),
				home.getFamilyId(), new IHttpCallBack() {
					@Override
					public void success(String result) {
						dimissProgressDialog();
						try {
							FamilyZoneResponse respone = new FamilyZoneResponse(
									new JSONObject(result));
							Common common = respone.getCommon();
							if (common == null) {

							} else if (common.getReturnCode().equals(
									BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
								familySpaceList = respone.getFamilySpaceList();
								if (familySpaceList != null) {
									head_grid.setNumColumns(familySpaceList
											.size());
									ViewTreeObserver vto = head_tools_linearlayout
											.getViewTreeObserver();
									vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
										@Override
										public void onGlobalLayout() {
											final int width = UIUtil
													.getDisplayWidth(FamilySpaceActivity.this) / 3;
											head_tools_linearlayout
													.getViewTreeObserver()
													.removeGlobalOnLayoutListener(
															this);
											final int coloumnNum = familySpaceList
													.size();
											date_grid_layout
													.setLayoutParams(new FrameLayout.LayoutParams(
															// 动态设置宽度
															width * coloumnNum,
															LinearLayout.LayoutParams.FILL_PARENT));
											head_tools_linearlayout
													.setThresholdWidth(width);
										}
									});
									familyUserAdapter = new FamilyUserAdapter(
											FamilySpaceActivity.this,
											familySpaceList);
									head_grid.setAdapter(familyUserAdapter);
									familyZoneInfoList = respone
											.getFamilyZoneInfoList();
									if (familyZoneInfoList == null) {
										familyZoneInfoList = new ArrayList<FamilyZoneInfo>();
									}
									if (selfPageFlag != null
											&& selfPageFlag
													.equals(Contants.ALBUM_TYPE_SELF)) {
										FamilyZoneInfo familyZoneInfo = new FamilyZoneInfo();
										familyZoneInfo
												.setZoneName(getString(R.string.familyspace_newphoto_text));
										familyZoneInfoList.add(familyZoneInfo);
									}
									familyPhotoGridAdapter = new FamilyPhotoGridAdapter(
											FamilySpaceActivity.this,
											familyZoneInfoList, selfPageFlag);
									photo_body
											.setAdapter(familyPhotoGridAdapter);
								}
							} else {
								Toast.makeText(FamilySpaceActivity.this,
										common.getErrorMsg(), Toast.LENGTH_LONG)
										.show();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void fail(String result) {
						dimissProgressDialog();
					}
				});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_familyspace);
		initView();
	}

	private void initView() {
		photo_body = (GridView) findViewById(R.id.photo_body);
		head_grid = (GridView) findViewById(R.id.head_grid);
		head_tools_linearlayout = (SpecialHorizontalScrollView) findViewById(R.id.head_tools_linearlayout);
		date_grid_layout = (LinearLayout) findViewById(R.id.date_grid_layout);
		homeDao = new HomeDao(this);
		if (getIntent().hasExtra(Contants.FAMILY_BEAN_PARAMS)) {
			family = (Family) getIntent().getSerializableExtra(
					Contants.FAMILY_BEAN_PARAMS);
		}
		selfPageFlag = getIntent().getStringExtra(Contants.SELF_PAGE_FLAG);
		if (family == null) {
			Log.e(TAG, "传入family参数有问题，该页面无法打开~");
			finish();
		}
		setActionBarTitle(R.string.see_familyspace_title_text);
		ButtonClick buttonClick = new ButtonClick();
		if (selfPageFlag != null
				&& selfPageFlag.equals(Contants.ALBUM_TYPE_SELF)) {
			setRightTextAndClickEvent1(getString(R.string.manage_title_text),
					buttonClick);
		}
		ClickItemEvent clickItemEvent = new ClickItemEvent();
		HeaderItemEvent headerItemEvent = new HeaderItemEvent();
		photo_body.setOnItemClickListener(clickItemEvent);
		head_grid.setOnItemClickListener(headerItemEvent);
		createMenu();
	}

	class ButtonClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {
			case R.id.righttext_1:
				openPanel(false);
				isManageFlag = true;
				familyPhotoGridAdapter.setManager(isManageFlag);
				break;
			case R.id.update_name_text:
				if (FamilyPhotoGridAdapter.chooseData.size() == 0) {
					Toast.makeText(FamilySpaceActivity.this, "没有选择空间",
							Toast.LENGTH_LONG).show();
					break;
				} else if (FamilyPhotoGridAdapter.chooseData.size() > 1) {
					Toast.makeText(FamilySpaceActivity.this, "必须选择一个空间才能编辑",
							Toast.LENGTH_LONG).show();
					break;
				} else {
					intent = new Intent(
							Contants.UPDATEPHOTOALBUM_ACTIVITY_ACTION);
					intent.putExtra("photoInfo",
							FamilyPhotoGridAdapter.chooseData.get(0));
					intent.putExtra(Contants.USER_ID_PARAMS, family.getUserid());
					intent.putExtra(Contants.ALBUMORZONE_PARAMS,
							Contants.ZONE_TYPE);
					startActivity(intent);
					isManageFlag = false;
					familyPhotoGridAdapter.setManager(isManageFlag);
					closePanel();
				}
				break;
			case R.id.delete_text:
				if (FamilyPhotoGridAdapter.chooseData.size() == 0) {
					Toast.makeText(FamilySpaceActivity.this, "没有选择空间",
							Toast.LENGTH_LONG).show();
					break;
				} else {
					String zoneIdArray = "";
					for (FamilyZoneInfo familyZoneInfo : FamilyPhotoGridAdapter.chooseData) {
						zoneIdArray += familyZoneInfo.getZoneId() + ",";
					}
					zoneIdArray = zoneIdArray.substring(0,
							zoneIdArray.lastIndexOf(","));
					showProgressDialog();
					new AlbumManagerRequest().excute(FamilySpaceActivity.this,
							family.getUserid(), "3", zoneIdArray, null, null,
							null, "2", new IHttpCallBack() {
								@Override
								public void success(String result) {
									dimissProgressDialog();
									try {
										dimissProgressDialog();
										Common common = new Common(
												new JSONObject(result));
										if (common
												.getReturnCode()
												.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
											resume();
										}
										Toast.makeText(
												FamilySpaceActivity.this,
												common.getErrorMsg(),
												Toast.LENGTH_LONG).show();
									} catch (JSONException e) {
										e.printStackTrace();
									}
								}

								@Override
								public void fail(String result) {
									dimissProgressDialog();
								}
							});
				}
				isManageFlag = false;
				familyPhotoGridAdapter.setManager(isManageFlag);
				closePanel();
				break;
			case R.id.delete_all_text:
				if (familyZoneInfoList == null
						|| familyZoneInfoList.size() == 0) {
					Toast.makeText(FamilySpaceActivity.this, "没有空间可删除~",
							Toast.LENGTH_LONG).show();
					break;
				}
				String zoneIdArray = "";
				for (FamilyZoneInfo familyZoneInfo : familyZoneInfoList) {
					if (familyZoneInfo.getZoneId() != null) {
						zoneIdArray += familyZoneInfo.getZoneId() + ",";
					}
				}
				zoneIdArray = zoneIdArray.substring(0,
						zoneIdArray.lastIndexOf(","));
				showProgressDialog();
				new AlbumManagerRequest().excute(FamilySpaceActivity.this,
						family.getUserid(), "3", zoneIdArray, null, null, null,
						"2", new IHttpCallBack() {
							@Override
							public void success(String result) {
								dimissProgressDialog();
								try {
									dimissProgressDialog();
									Common common = new Common(new JSONObject(
											result));
									if (common
											.getReturnCode()
											.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										resume();
									}
									Toast.makeText(FamilySpaceActivity.this,
											common.getErrorMsg(),
											Toast.LENGTH_LONG).show();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								dimissProgressDialog();
							}
						});
				isManageFlag = false;
				familyPhotoGridAdapter.setManager(isManageFlag);
				closePanel();
				break;
			case R.id.sure_or_cannelbutton:
				isManageFlag = false;
				familyPhotoGridAdapter.setManager(isManageFlag);
				closePanel();
				break;
			case R.id.son_linearlayout:
				intent = new Intent(Contants.CHILDSPACE_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			default:
				break;
			}
		}

	}

	private void createMenu() {
		View view = LayoutInflater.from(FamilySpaceActivity.this).inflate(
				R.layout.menu_familyspace_edit, null);
		ButtonClick buttonClick = new ButtonClick();
		update_name_text = (TextView) view.findViewById(R.id.update_name_text);
		delete_text = (TextView) view.findViewById(R.id.delete_text);
		delete_all_text = (TextView) view.findViewById(R.id.delete_all_text);
		sure_or_cannelbutton = (Button) view
				.findViewById(R.id.sure_or_cannelbutton);
		update_name_text.setOnClickListener(buttonClick);
		delete_text.setOnClickListener(buttonClick);
		delete_all_text.setOnClickListener(buttonClick);
		sure_or_cannelbutton.setOnClickListener(buttonClick);
		setMenuLayout(view);
	}

	class HeaderItemEvent implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			UserDao userDao = new UserDao(FamilySpaceActivity.this);
			User user = userDao.getCurrentUser(LoveHomeApplication.token);
			FamilySpace familySpace = familySpaceList.get(position);
			if (familySpace.getNonage().equals("Y")) {
				Intent intent = new Intent(Contants.CHILDSPACE_ACTIVITY_ACTION);
				intent.putExtra(Contants.USERINFOFLAG_STRING, familySpace);
				startActivity(intent);
			} else if (!user.getUser_id().equals(familySpace.getId())) {
				startActivity(new Intent(FamilySpaceActivity.this,
						ChatActivity.class).putExtra("userId",
						familySpace.getId()).putExtra("familySpace",
						familySpace));
			}

		}
	}

	class ClickItemEvent implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			FamilyZoneInfo familyZoneInfo = familyZoneInfoList.get(position);
			if (selfPageFlag != null
					&& selfPageFlag.equals(Contants.ALBUM_TYPE_SELF)) {
				if (isManageFlag) {
					FamilyPhotoGridAdapter.ViewHodler viewHolder = (FamilyPhotoGridAdapter.ViewHodler) view
							.getTag();
					viewHolder.getChoose_photo_checkbox().setChecked(
							!viewHolder.getChoose_photo_checkbox().isChecked());
					return;
				}
				if (position != (parent.getAdapter().getCount() - 1)) {
					Intent intent = new Intent(
							Contants.PERSONALALBUM_ACTIVITY_ACTION);
					intent.putExtra(Contants.PAGEFLAG_STRING,
							Contants.ALBUM_TYPE_SELF);
					intent.putExtra(Contants.TITLE_PARAMS,
							familyZoneInfo.getZoneName());
					intent.putExtra(Contants.ZONE_ID_PARAMS,
							familyZoneInfo.getZoneId());
					intent.putExtra(Contants.USER_ID_PARAMS, family.getUserid());
					startActivity(intent);
				} else {
					Intent intent = new Intent(
							Contants.NEWPHOTOALBUM_ACTIVITY_ACTION);
					intent.putExtra(Contants.USER_ID_PARAMS, family.getUserid());
					intent.putExtra(Contants.ALBUMORZONE_PARAMS,
							Contants.ZONE_TYPE);
					startActivity(intent);
				}
			} else {
				Intent intent = new Intent(
						Contants.FAMILY_PHOTO_ACTIVITY_ACTION);
				intent.putExtra(Contants.PAGEFLAG_STRING,
						Contants.ALBUM_TYPE_SELF);
				intent.putExtra(Contants.ZONE_ID_PARAMS,
						familyZoneInfo.getZoneId());
				intent.putExtra(Contants.USER_ID_PARAMS, family.getUserid());
				startActivity(intent);
			}
		}
	}
}
